﻿using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Security;
using NSubstitute;
using NUnit.Framework;

namespace FormsAuthenticationExtensions.Tests
{
    [TestFixture]
    public class RoundtripTests
    {
        [Test]
        public void StringRoundtrip()
        {
            const string userData = "foo bar 123";

            var response = Substitute.For<HttpResponseBase>();
            var cookies = new HttpCookieCollection();
            response.Cookies.Returns(cookies);

            new FormsAuthentication().SetAuthCookie(response, "user name", false, userData);

            var ticket = FormsAuthentication.Decrypt(cookies.Get(0).Value);
            var returnedUserData = ticket.UserData;

            Assert.AreEqual(userData, returnedUserData);
        }

        [Test]
        public void NameValueCollectionRoundtrip()
        {
            var userData = new NameValueCollection
            {
                { "foo", "bar" },
                { "baz", "123" },
            };

            var response = Substitute.For<HttpResponseBase>();
            var cookies = new HttpCookieCollection();
            response.Cookies.Returns(cookies);

            new FormsAuthentication().SetAuthCookie(response, "user name", false, userData);

            var ticket = FormsAuthentication.Decrypt(cookies.Get(0).Value);
            var returnedUserData = ticket.GetStructuredUserData();

            CollectionAssert.AreEqual(
                userData.AllKeys.OrderBy(k => k).ToArray(),
                returnedUserData.AllKeys.OrderBy(k => k).ToArray()
            );
            CollectionAssert.AreEqual(
                userData.AllKeys.OrderBy(k => k).Select(k => userData[k]).ToArray(),
                returnedUserData.AllKeys.OrderBy(k => k).Select(k => userData[k]).ToArray()
            );
        }
    }
}
